using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using LiteTools.domains;

namespace LiteTools.tools
{
    public class DataUtil
    {
        private static int currentLen;

        public static FormatData GenTlvDataFromTreeView(TreeNode treeNode)
        {
            var treeNodeName = treeNode.Name;
            if (treeNodeName != "root")
            {
                // 错了，第一个必须是root
            }

            var rootNode = treeNode.Nodes[0];
            var tlvData = new TlvData
            {
                Tag = "root",
                Level = 0,
                TlvList = new List<TlvData>()
            };
            currentLen = 0;
            var genChildren = GenChildren(rootNode, 1, out var len);
            genChildren.Length = NumberUtils.GetHexStr(len).Substring(2);
            tlvData.TlvList.Add(genChildren);
            return tlvData;
        }

        /// <summary>
        /// 处理节点
        /// </summary>
        /// <param name="rootNode"> 需要处理的节点 </param>
        /// <param name="index"></param>
        private static TlvData GenChildren(TreeNode rootNode, int index, out int length)
        {
            // 每次构建一个新的TLV数据的时候先把长度设置为0
            length = 0;
            var tlvData = new TlvData
            {
                Tag = rootNode.Name,
                Level = index,
                TlvList = new List<TlvData>()
            };
            foreach (TreeNode node in rootNode.Nodes)
            {
                // 这是一个基础节点，不需要向下解析
                if (node.Tag != null && !string.IsNullOrEmpty(node.Tag.ToString()))
                {
                    var data = new TlvData
                    {
                        Tag = node.Name,
                        Length = NumberUtils.GetHexStr(node.Tag.ToString().Length / 2).Substring(2),
                        Level = index + 1,
                        Value = node.Tag.ToString()
                    };
                    length +=
                        (node.Tag.ToString().Length + node.Name.Length) / 2  + TlvUtil.GetLengthHex(data.Length).Length / 2;
                    tlvData.TlvList.Add(data);
                    continue;
                }

                var genChildren = GenChildren(node, index + 1, out var dataLen);
                genChildren.Length = NumberUtils.GetHexStr(dataLen).Substring(2);
                length += dataLen + node.Name.Length / 2 + TlvUtil.GetLengthHex(dataLen.ToString()).Length / 2;
                tlvData.TlvList.Add(genChildren);
            }

            return tlvData;
        }

        private static string GetHeader(int numOfSpace)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < numOfSpace; i++)
            {
                builder.Append("\t");
            }

            return builder.ToString();
        }
    }
}